<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomTag\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\RoomTag\Contract\RoomTagContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagGroupContract;
use MoChat\Plugin\RoomTag\Contract\RoomTagPivotContract;

/**
 * 修改客户群标签.
 *
 * Class Update
 * @Controller
 */
class Update extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var RoomTagGroupContract
     */
    protected $roomTagGroupService;

    /**
     * @Inject
     * @var RoomTagContract
     */
    protected $roomTagService;

    /**
     * @Inject
     * @var RoomTagPivotContract
     */
    protected $roomTagPivotService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/roomTag/update", methods="PUT")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['groupName'] = $this->request->input('groupName', '');
        $params['id'] = $this->request->input('id');
        $params['tags'] = $this->request->input('tags');
        $params['deleteTags'] = $this->request->input('deleteTags', []);

        // 验证参数
        $this->validated($params);

        // 处理参数
        [$createDate, $updateData] = $this->handleParam($user, $params);

        // 数据操作
        Db::beginTransaction();
        try {
            // 创建群标签组
            $this->roomTagGroupService->updateRoomTagGroupById($params['id'], ['group_name' => $params['groupName']]);
            // 添加群标签
            if (! empty($createDate)) {
                $this->roomTagService->createRoomTags($createDate);
            }
            // 修改群标签
            if (! empty($updateData)) {
                $this->roomTagService->updateRoomTag($updateData);
            }
            // 删除标签
            if (! empty($params['deleteTags'])) {
                $tagIds = array_column($params['deleteTags'], 'id');
                $this->roomTagService->deleteRoomTags($tagIds);
                // 删除客户群标签
                $this->roomTagPivotService->deleteRoomTagPivotByRoomTagId($tagIds);
            }

            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '修改群标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'id' => 'required|integer',
            'groupName' => 'required|string',
            'tags' => 'required|array',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'id.required' => '标签组id 必传',
            'groupName.required' => '标签组名称 必传',
            'tags.required' => '标签名称 必传',
        ];
    }

    /**
     * 处理参数.
     * @param array $user 用户信息
     * @param array $params 接受参数
     */
    private function handleParam(array $user, array $params): array
    {
        // 校验标签组名称重复
        if (! empty($params['groupName']) && ! empty($this->roomTagGroupService->getRoomTagGroupByCorpIdName($user['corpIds'][0], $params['groupName'], $params['id']))) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '标签组名称重复，不可操作');
        }

        $createData = [];
        $updateData = [];
        foreach ($params['tags'] as $item) {
            if (isset($item['id'])) {
                if (! empty($this->roomTagService->getRoomTagByGroupIdName($params['id'], $item['name'], $item['id']))) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '标签名称重复:' . $item['name']);
                }
                $updateData[] = $item;
            } else {
                if (! empty($this->roomTagService->getRoomTagByGroupIdName($params['id'], $item['name']))) {
                    throw new CommonException(ErrorCode::INVALID_PARAMS, '不可创建同名标签:' . $item['name']);
                }
                $createData[] = [
                    'name' => $item['name'],
                    'room_tag_group_id' => $params['id'],
                    'corp_id' => user()['corpIds'][0],
                    'tenant_id' => user('tenantId'),
                    'created_at' => date('Y-m-d H:i:s'),
                ];
            }
        }
        return [$createData, $updateData];
    }
}
